package com.smartHire.controller;

import com.alibaba.fastjson.JSONObject;
import com.smartHire.domain.User;
import com.smartHire.service.UserService;
import com.smartHire.util.AesUtil;
import com.smartHire.util.HttpRequest;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Dictionary;
import java.util.Map;


@WebServlet(name = "UserRegisterServlet", value = "/UserRegisterServlet")
public class UserRegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = request.getParameter("code");
        System.out.println(code);
        String userInfo = request.getParameter("userInfo");
        System.out.println(userInfo);


        String appid = "wxb2e2dd25172ffcc6";
        String secret = "e6aa55b629d9e6b9f0885d5f75b8416f";
        String js_code = code;
        String grant_type = "authorization_code";

        String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");
        System.out.println("openid:" + openid);

        WebApplicationContext ctx = null;
        //使用框架中的方法，获取容器对象
        ServletContext sc = getServletContext();
        ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

        try {


            //获取service
            UserService service  = (UserService) ctx.getBean("userService");

            User user = new User();
            user.setU_Id(openid);

            Map map = (Map)JSONObject.parse(userInfo);
            user.setName((String) map.get("nickName"));
            user.setSex(map.get("gender").toString());
            user.setBalance(0);


            if (service.queryUserById(user)==null)
            {
                if(service.addUser(user)==1)
                {
                    System.out.println("用户注册成功");
                }
                else
                {
                    System.out.println("用户注册失败");

                }
            }
            else
            {
                System.out.println("用户已注册");
            }
            response.getWriter().write(openid);

        }catch (Exception e)
        {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



    }
}
